package net.sareweb.acab.entity.manager;

import java.util.List;

import net.sareweb.acab.entity.Seat;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("seatManager")
@Scope(ScopeType.CONVERSATION)
public class SeatManager extends CommonManager<Seat> {
	
	public Seat findByTravelAndSeatNumber(Integer idTravel, Integer seatNumber){
		return  (Seat) entityManager.createQuery(_FIND_BY_TRAVEL_AND_SEATNUMBER)
		.setParameter("idTravel", idTravel)
		.setParameter("seatNumber", seatNumber).getSingleResult();
	}
	
	public boolean releaseSeat(Integer idSeat){
		Seat s = this.find(idSeat);
		if(s==null) return false;
		s.setUser(null);
		s.setState(SEAT_STATE_FREE);
		this.save(s);
		return true;
	}
	
	public boolean releaseSeatByTravelAndUser(Integer idTravel, Integer idUser){
		List <Seat> seats = findByTravelAndUSer(idTravel, idUser);
		if(seats == null || seats.size()==0) return false;
		Seat s = seats.get(0);
		s.setUser(null);
		s.setState(SEAT_STATE_FREE);
		this.save(s);
		return true;
	}
	
	
	
	@SuppressWarnings("unchecked")
	public List<Seat> findByTravelAndUSer(Integer idTravel, Integer idUser){
		return  entityManager.createQuery(_FIND_BY_TRAVEL_AND_USER)
		.setParameter("idTravel", idTravel)
		.setParameter("idUser", idUser).getResultList();
		
	}
	
	private String _FIND_BY_TRAVEL_AND_SEATNUMBER="from Seat where  travel.idTravel=:idTravel and seatNumber=:seatNumber";
	private String _FIND_BY_TRAVEL_AND_USER="from Seat where  travel.idTravel=:idTravel and user.idUser=:idUser";
	
	
	public static final String SEAT_STATE_FREE= 	"FREE";
	public static final String SEAT_STATE_OCCUPIED= "OCCUPIED";
	public static final String SEAT_STATE_DISABLED= "DISABLED";
	
	
}
